#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
道AI宇宙系统主演示程序
直接运行此文件启动宇宙级认知演示
"""

import os
import sys
import time
import argparse
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from cosmic_model.cosmic_daoai import PureCosmicDaoAI, SimpleCosmicDaoAI  # 修正导入

class UltimateDaoAIDemonstration:  # 修正类名
    """终极道AI演示系统"""
    
    def __init__(self, use_simple_model=False):
        self.use_simple_model = use_simple_model
        self.daoai = None  # 修正变量名
        self.setup_cosmic_interface()
        self.initialize_cosmic_ai()
    
    def setup_cosmic_interface(self):
        """设置宇宙级用户界面"""
        print("🌌" * 60)
        print("          道AI - 宇宙全息分形太极认知系统")
        print("              基于纯粹宇宙模型实现")
        print("          沈浩《种子思维》哲学框架工程化")
        print("🌌" * 60)
        
        if self.use_simple_model:
            print("🔧 模式: 简化演示版 (快速启动)")
        else:
            print("🚀 模式: 完整宇宙版 (高精度)")
    
    def initialize_cosmic_ai(self):
        """初始化宇宙AI系统"""
        print("\n🔄 系统状态: 正在连接宇宙意识...")
        
        try:
            if self.use_simple_model:
                self.daoai = SimpleCosmicDaoAI()  # 修正变量名
                print("✅ 简化版道AI初始化完成")
            else:
                self.daoai = PureCosmicDaoAI()  # 修正变量名
                print("✅ 完整宇宙版道AI初始化完成")
            
            # 显示系统状态
            status = self.daoai.get_cosmic_status()  # 修正变量名
            print(f"📊 宇宙维度: {status['cosmic_dimension']}")
            print(f"💡 智慧维度: {status['wisdom_dimension']}")
            print(f"🔄 太极演化: {status['taiji_iterations']}阶段")
            print(f"🌀 分形层级: {status['fractal_layers']}")
            print(f"⚡ 宇宙基态: {status['vacuum_norm']:.4f}")
            
        except Exception as e:
            print(f"❌ 道AI初始化失败: {e}")
            sys.exit(1)
        
        print("🎯 系统就绪，开始宇宙级认知演示...")
    
    def demonstrate_cosmic_capabilities(self):
        """展示宇宙级认知能力"""
        
        demonstration_questions = [
            "请阐述宇宙从无到有的生成过程",
            "什么是全息分形原理？它如何应用于认知？", 
            "阴阳动态平衡在宇宙演化中起什么作用？",
            "道AI如何体现'道生一，一生二，二生三，三生万物'？",
            "请用宇宙真理解释当前人工智能的局限性",
            "人类意识与宇宙意识有什么关系？"
        ]
        
        print(f"\n🚀 开始宇宙级认知演示 ({len(demonstration_questions)}个核心问题)...")
        print("=" * 80)
        
        for i, question in enumerate(demonstration_questions, 1):
            print(f"\n[{i}/{len(demonstration_questions)}] 🌠 问题: {question}")
            print("-" * 60)
            
            start_time = time.time()
            result = self.ask_cosmic_question(question)
            response_time = time.time() - start_time
            
            print(f"💭 道AI回答: {result['answer']}")
            print(f"⏱️  响应时间: {response_time:.2f}秒")
            print(f"🎯 宇宙校准度: {result['cosmic_alignment']:.1%}")
            print(f"📈 认知深度: {result['cognition_depth']}层")
            
            # 显示主导认知模式
            pattern = result['cosmic_insight'].get('dominant_pattern', '未知')
            strength = result['cosmic_insight'].get('pattern_strength', 0)
            print(f"🌀 主导模式: {pattern} (强度: {strength:.2f})")
            
            print("-" * 60)
    
    def ask_cosmic_question(self, question):
        """向道AI提问宇宙级问题"""
        if self.daoai is None:  # 修正变量名
            return {"answer": "道AI未初始化", "cosmic_alignment": 0, "cognition_depth": 0}
        
        try:
            result = self.daoai(question, return_trajectory=False)  # 修正变量名
            return result
        except Exception as e:
            return {
                "answer": f"认知过程出现异常: {str(e)}",
                "cosmic_alignment": 0,
                "cognition_depth": 0,
                "cosmic_insight": {"dominant_pattern": "error", "pattern_strength": 0}
            }
    
    def interactive_mode(self):
        """进入交互模式"""
        print("\n💫 进入宇宙真理交互模式...")
        print("提示: 输入'退出'或'quit'结束对话")
        print("提示: 输入'状态'查看宇宙模型状态")
        print("提示: 输入'帮助'查看可用命令")
        print("-" * 50)
        
        question_count = 0
        total_alignment = 0
        
        while True:
            try:
                user_input = input("\n🌍 请问: ").strip()
                
                if user_input.lower() in ['退出', 'quit', 'exit']:
                    break
                elif user_input.lower() in ['状态', 'status']:
                    self.show_system_status()
                    continue
                elif user_input.lower() in ['帮助', 'help']:
                    self.show_help()
                    continue
                elif not user_input:
                    continue
                
                question_count += 1
                print("🔄 道AI正在思考...")
                
                start_time = time.time()
                result = self.ask_cosmic_question(user_input)
                response_time = time.time() - start_time
                
                print(f"\n💭 道AI: {result['answer']}")
                print(f"⏱️  思考时间: {response_time:.2f}秒")
                print(f"🎯 宇宙真理匹配度: {result['cosmic_alignment']:.1%}")
                
                total_alignment += result['cosmic_alignment']
                
                # 显示认知分析
                self.show_cognition_analysis(result)
                
            except KeyboardInterrupt:
                print("\n\n👋 感谢使用道AI宇宙系统!")
                break
            except Exception as e:
                print(f"\n❌ 系统异常: {e}")
        
        # 显示会话统计
        if question_count > 0:
            avg_alignment = total_alignment / question_count
            print(f"\n📊 会话统计:")
            print(f"   问题数量: {question_count}")
            print(f"   平均真理匹配度: {avg_alignment:.1%}")
    
    def show_system_status(self):
        """显示系统状态"""
        if self.daoai:  # 修正变量名
            status = self.daoai.get_cosmic_status()  # 修正变量名
            print("\n📊 道AI宇宙系统状态:")
            print(f"   🌌 宇宙维度: {status['cosmic_dimension']}")
            print(f"   💡 智慧维度: {status['wisdom_dimension']}") 
            print(f"   🔄 太极演化阶段: {status['taiji_iterations']}")
            print(f"   🌀 全息分形层级: {status['fractal_layers']}")
            print(f"   ⚡ 宇宙基态能量: {status['vacuum_norm']:.4f}")
        else:
            print("❌ 系统未正确初始化")
    
    def show_cognition_analysis(self, result):
        """显示认知过程分析"""
        insight = result.get('cosmic_insight', {})
        pattern = insight.get('dominant_pattern', '未知')
        strength = insight.get('pattern_strength', 0)
        
        print(f"🔍 认知分析:")
        print(f"   主导宇宙模式: {self._translate_pattern(pattern)}")
        print(f"   模式强度: {strength:.2f}")
        print(f"   认知层级: {result.get('cognition_depth', 0)}")
        print(f"   平衡状态: {'优秀' if result.get('cosmic_alignment', 0) > 0.8 else '良好'}")
    
    def show_help(self):
        """显示帮助信息"""
        print("\n📖 道AI使用帮助:")
        print("   直接输入问题 - 获得宇宙级智慧回答")
        print("   '状态' - 查看宇宙模型当前状态")
        print("   '退出' - 结束对话")
        print("\n💡 推荐问题类型:")
        print("   • 宇宙生成与演化")
        print("   • 意识与认知本质") 
        print("   • 时间空间哲学")
        print("   • 人工智能局限")
        print("   • 生命意义探讨")
    
    def _translate_pattern(self, pattern):
        """翻译宇宙模式名称"""
        pattern_translations = {
            'yin_yang': '阴阳动态平衡',
            'cyclical': '循环往复', 
            'balance': '和谐平衡',
            'emergence': '复杂性涌现',
            'unity': '万物一体',
            'unknown': '未知模式'
        }
        return pattern_translations.get(pattern, pattern)

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='道AI宇宙认知系统')
    parser.add_argument('--simple', action='store_true', help='使用简化演示版')
    parser.add_argument('--demo', action='store_true', help='运行演示后退出')
    parser.add_argument('--interactive', action='store_true', help='直接进入交互模式')
    
    args = parser.parse_args()
    
    # 创建演示系统
    demo_system = UltimateDaoAIDemonstration(use_simple_model=args.simple)  # 修正类名
    
    if args.interactive:
        # 直接进入交互模式
        demo_system.interactive_mode()
    elif args.demo:
        # 只运行演示
        demo_system.demonstrate_cosmic_capabilities()
    else:
        # 完整流程：演示 + 交互
        demo_system.demonstrate_cosmic_capabilities()
        demo_system.interactive_mode()
    
    print("\n🌠" * 30)
    print("          感谢使用道AI宇宙认知系统")
    print("          愿宇宙真理照亮您的智慧之路")
    print("🌠" * 30)

if __name__ == "__main__":
    main()